package com.lv.service.utils

import android.content.Context
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.workDataOf
import com.blankj.utilcode.util.SPStaticUtils
import com.lv.common.ktx.ContainsSelf

import com.lv.common.utils.Constants
import com.lv.service.bean.CardBackImageBean

import com.lv.service.repo.UserInfo
import com.lv.service.room.address.AddressBean
import com.lv.service.room.address.AddressCurrentDbHelper
import com.lv.service.room.address.AddressDbHelper
import com.lv.service.room.address.CurrentAddress
import com.lv.service.room.address.LocationNewReceiptAddressDbHelper
import com.lv.service.room.address.ReceiptAddressItem
import com.lv.service.room.card.CardAddressBean
import com.lv.service.room.card.CardAddressDbHelper
import com.lv.service.room.card.CardCategoryBean
import com.lv.service.room.card.CardCategoryDbHelper
import com.lv.service.room.card.CardColorBean
import com.lv.service.room.card.CardColorDbHelper
import com.lv.service.room.category.CategoryBean
import com.lv.service.room.category.CategoryDbHelper
import com.lv.service.room.category.NewTelCategoryBean
import com.lv.service.room.category.NewTelCategoryCityDbHelper
import com.lv.service.room.category.NewTelCategoryDbHelper
import com.lv.service.room.category.SpuCategoryBean
import com.lv.service.room.category.SpuCategoryDbHelper
import com.lv.service.workmanager.LoadInfoWorker

/**
 * 作者： ygx
 * 创建日期：2023/2/11 2:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class YgxRoomToolsKt {

    companion object {

        /*fun findProsNewReceiptAddress(
            context: Context,
            viewModuleService: ServiceViewModel,
            myScope: CoroutineScope,
            lifecycleScope: LifecycleCoroutineScope
        ) {
            val map = mutableMapOf<String, String>(
                "newreceiptAddress" to "1",
            )
            lifecycleScope.launchWhenCreated {
                this.launch {
                    val result: DataResult<BaseYgxRsp> =
                        myScope.async { viewModuleService.findPros(map) }.await()
                    parseFindProsResult(context, result, lifecycleScope)
                }
            }
        }

        private fun parseFindProsResult(
            context: Context,
            data: DataResult<BaseYgxRsp>,
            lifecycleScope: LifecycleCoroutineScope
        ) {
            data.onSuccess {
                onBizOK<FindProsBean> { code, data, message, result ->
                    data?.let {

                        lifecycleScope.launch {

                            //四级地址选择器数据
                            this.launch {
                                val addressList = it.newreceiptAddress
                                if (addressList != null) {
                                    saveNewReceiptAddressAllRoom(context, addressList)
                                }
                            }


                        }
                    }

                }
                onBizError<FindProsBean> { code, message, data ->
                    showToast(message)
                }
            }
            data.onFailure {
                LogUtils.e("eee")
            }
        }*/

        /**
         * 存地址到数据库
         */
        suspend fun saveNewReceiptAddressAllRoom(
            context: Context,
            addressList: List<ReceiptAddressItem>,
        ) {
//            LocationNewReceiptAddressDbHelper.deleteAllLocation(context)
            val addressBeans = mutableListOf<ReceiptAddressItem>()
            for ((index, e) in addressList.withIndex()) {
                val addressBean = ReceiptAddressItem(
                    index,
                    e.id,
                    e.name,
                    e.firstChar,
                    e.forshort,
                    e.pforshort,
                    e.seq,
                    e.centre,
                    e.isShow,
                    e.telSecondCategories,
                )
                addressBeans.add(addressBean)
            }
            LocationNewReceiptAddressDbHelper.insertAllLocation(
                context,
                addressBeans
            )
        }

        /**
         * 存分类到数据库
         */
        suspend fun saveRoomCategory(context: Context, categoryList: List<CategoryBean>) {
            val categoryBeans = mutableListOf<CategoryBean>()
            for ((index, e) in categoryList.withIndex()) {
                val categoryBean = CategoryBean(
                    index,
                    e.fcaid,
                    e.id,
                    e.forshort,
                    e.image,
                    e.name,
                    e.seq,
                    e.telSecondCategories,
                    e.isSelcted
                )
                categoryBeans.add(categoryBean)
            }
            CategoryDbHelper.insertAllCategory(
                context, categoryBeans
            )
        }

        /**
         * 存找货大全分类到数据库
         */
        suspend fun saveCardCategory(context: Context, categoryList: List<CardCategoryBean>) {
//            CardCategoryDbHelper.deleteSuspendAllCategory(context)
            val categoryBeans = mutableListOf<CardCategoryBean>()
            for ((index, e) in categoryList.withIndex()) {
                val categoryBean = CardCategoryBean(
                    index,
                    e.fcaid,
                    e.id,
                    e.image,
                    e.name,
                    e.seq,
                    e.telSecondCategories,
                    e.isSelcted
                )
                categoryBeans.add(categoryBean)
            }
            CardCategoryDbHelper.insertAllCategory(
                context,
                categoryBeans
            )
        }

        /**
         * 存新分类数据到数据库
         */
        suspend fun saveNewTelCategoryRoom(
            context: Context,
            newTelCategoryBean: List<NewTelCategoryBean>
        ) {
//            val addressBeans = mutableListOf<NewTelCategoryBean>()
//            for ((index, e) in newTelCategoryBean.withIndex()) {
//                val addressBean = NewTelCategoryBean(
//                    index, e.id, e.fcaid, e.name, e.seq, e.image, e.isSelcted
//                )
//                addressBeans.add(addressBean)
//            }
            NewTelCategoryDbHelper.insertAllCategory(
                context, newTelCategoryBean
            )
        }

        /**
         * 存新分类数据到数据库
         */
        suspend fun saveNewTelCategoryCityRoom(
            context: Context,
            newTelCategoryBean: List<NewTelCategoryBean>
        ) {
            NewTelCategoryCityDbHelper.insertAllCategory(
                context, newTelCategoryBean
            )
        }

        /**
         * 存地址到数据库
         */
        suspend fun saveAddressRoom(context: Context, addressList: List<CategoryBean>) {
            val addressBeans = mutableListOf<AddressBean>()
            for ((index, e) in addressList.withIndex()) {
                val telSecondCategories = e.telSecondCategories
                val size = telSecondCategories?.size ?: 0
                if (size > 0) {
                    for (i in 0 until telSecondCategories!!.size) {
                        telSecondCategories[i].image = e.name
                    }
                }
                val addressBean = AddressBean(
                    index,
                    e.id,
                    e.image?:"",
                    e.name?:"",
                    telSecondCategories,
                    e.isSelcted
                )
                addressBeans.add(addressBean)
            }
            AddressDbHelper.insertFindSuspendCategory(
                context,
                addressBeans
            )
        }

        /**
         * 存商品分类到数据库
         */
        suspend fun saveGoodsCategory(context: Context, categoryList: List<SpuCategoryBean>) {
            val categoryBeans = mutableListOf<SpuCategoryBean>()
            for ((index, e) in categoryList.withIndex()) {
                val categoryBean = SpuCategoryBean(
                    index,
                    e.fcaid,
                    e.id,
                    e.image,
                    e.name,
                    e.seq,
                    e.telSecondCategories,
                    e.isSelcted
                )
                categoryBeans.add(categoryBean)
            }
            SpuCategoryDbHelper.insertAllCategory(
                context, categoryBeans
            )
        }

        /**
         * 存名片地址到数据库
         */
        suspend fun saveCardAddress(context: Context, addressList: List<CardAddressBean>) {
            val addressBeans = mutableListOf<CardAddressBean>()
            for ((index, e) in addressList.withIndex()) {
                val addressBean = CardAddressBean(
                    index,
                    e.fcaid,
                    e.id,
                    e.image,
                    e.name,
                    e.seq,
                    e.telSecondCategories,
                    e.isSelcted,
                )
                addressBeans.add(addressBean)
            }
            CardAddressDbHelper.insertFindSuspendCategory(
                context,
                addressBeans
            )
        }

        /**
         * 存名片信息到数据库
         */
        suspend fun saveCardColorInfo(context: Context, cardColorList: List<CardColorBean>) {
            val cardColorBeans = mutableListOf<CardColorBean>()
            for ((index, e) in cardColorList.withIndex()) {
                val cardColorBean = CardColorBean(
                    index,
                    e.id,
                    e.enterpage,
                    e.buypage,
                    e.listpage,
                    e.cardpage,
                    e.newcardpage,
                )
                cardColorBeans.add(cardColorBean)
            }
            CardColorDbHelper.insertAllCardColor(
                context,
                cardColorBeans
            )
        }


        /**
         * 执行后台任务
         */
        fun doWorkManager(context: Context, isRefresh: String = "-1") {
            val upLoadInfoWorkerRequest: WorkRequest =
                OneTimeWorkRequestBuilder<LoadInfoWorker>()
                    .setInputData(workDataOf("name" to isRefresh))
                    .build()
            WorkManager.getInstance(context).enqueue(upLoadInfoWorkerRequest)
        }

        fun UserInfo?.isLogin(): Boolean {
            if (this == null) {
                return false
            }
            val length = id?.length ?: 0
            return length != 0
        }


        /**
         * 保存定位
         */
        fun saveLoction(
            context: Context,
            forshort: String?,
            province: String?,
            city: String?,
            area: String?,
            locationLat: String?,
            locationLon: String?
        ) {
//        mCurrentProvince = province ?: ""
            SPStaticUtils.put(Constants.SP_KEY_ADDRESS_PROVINCE_FORSHORT, forshort)
            SPStaticUtils.put(Constants.SP_KEY_ADDRESS_PROVINCE, province)
            SPStaticUtils.put(Constants.SP_KEY_ADDRESS_CITY, city)
            SPStaticUtils.put(Constants.SP_KEY_ADDRESS_AREA, area)
            SPStaticUtils.put(
                Constants.SP_KEY_ADDRESS_TIME,
                System.currentTimeMillis()
            ) //最后一次成功获取定位的时间
//            SPStaticUtils.put(Constants.LOCATION_TIME_KEY, System.currentTimeMillis()) //保存上次定位时间的key
            SPStaticUtils.put(Constants.SP_KEY_ADDRESS_LAT, locationLat) //保存定位的径度
            SPStaticUtils.put(Constants.SP_KEY_ADDRESS_LON, locationLon) //保存定位的纬度
            AddressCurrentDbHelper.insertAddress(
                context,
                CurrentAddress(
                    0, forshort, province, city,
                    area, System.currentTimeMillis(), locationLat, locationLon
                )
            )
        }

        //是否是省会
        fun filterCentreByCity(
            mAddress: MutableList<ReceiptAddressItem>,
            searchString: String
        ): Boolean {
            var center = false
            for (address in mAddress) {
                val telSecondCategories = address.telSecondCategories
                if (!telSecondCategories.isNullOrEmpty()) {
                    for (tel in telSecondCategories) {
                        val name = tel.name ?: ""
                        val centre = tel.centre ?: "0"
                        if (centre == "1" && name.ContainsSelf(searchString)) {
                            center = true
                            break
                        }
                    }
                }

            }
            return center
        }

//        //是否是地级市的中心城市
//        fun filterCentreByArea(
//            mAddress: MutableList<ReceiptAddressItem>,
//            city: String
//        ): Boolean {
//            var center = false
//            for (address in mAddress) {
//                val telSecondCategories = address.telSecondCategories
//                if (!telSecondCategories.isNullOrEmpty()) {
//                    for (tel in telSecondCategories) {
//                        val telCity = tel.name ?: ""
//                        if (telCity.ContainsSelf(city)){
//                            val telThirdCategories = tel.telThirdCategories
//                            if (telThirdCategories != null) {
//                                for (third in telThirdCategories) {
//                                    val name = third.name ?: ""
//                                    val centre = third.centre ?: "0"
//                                    if (centre == "1" && name.ContainsSelf(area)) {
//                                        center = true
//                                        break
//                                    }
//                                }
//                            }
//                        }
//
//                    }
//                }
//
//            }
//            return center
//        }

        //是否是市的中心城市
        fun filterCityCentreByArea(
            mAddress: MutableList<ReceiptAddressItem>,
            province: String, city: String, area: String
        ): Boolean {
            var center = false
            for (address in mAddress) {
                if (province.isNotEmpty()) {
                    val telPro = address.name
                    if (!province.ContainsSelf(telPro)) {
                        continue
                    }
                }
                val telSecondCategories = address.telSecondCategories
                if (!telSecondCategories.isNullOrEmpty()) {
                    for (tel in telSecondCategories) {
                        val telCity = tel.name ?: ""
                        val telThirdCategories = tel.telThirdCategories
                        if (telThirdCategories != null) {
                            for (third in telThirdCategories) {
                                val name = third.name ?: ""
                                val centre = third.centre ?: "0"
                                if (telCity.ContainsSelf(city)) {
                                    if (centre == "1" && name.ContainsSelf(area)) {
                                        center = true
                                        break
                                    }
                                }
                            }
                        }
                    }
                }

            }
            return center
        }

    }
}